package com.leyou.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.pojo.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;


    @Autowired
    private SpringTemplateEngine templateEngine;

    @Value("${ly.static.itemDir}")
    private String itemDir;
    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    /**
     * 查询模型数据
     *
     * @param spuId
     * @return
     */
    public Map<String, Object> loadItemData(Long spuId) {

        // 查询spu
        SpuDTO spuDTO = itemClient.querySpuById(spuId);
        // 查询分类集合
        List<CategoryDTO> categoryDTOS = null;
        try {
            categoryDTOS = itemClient.queryCategoryByIds(spuDTO.getCategoryIds());
        } catch (Exception e) {
            System.out.println("spuDTO = " + spuDTO);
            System.out.println("e = " + e);
            e.printStackTrace();
        }

        // 查询品牌
        BrandDTO brandDTO = itemClient.queryBrandById(spuDTO.getBrandId());
        // 查询规格
        List<SpecGroupDTO> specGroupDTOS = itemClient.querySpecsByCid(spuDTO.getCid3());

        //根据spu的id查询sku集合
        List<SkuDTO> skuDTOS = itemClient.querySkuBySpuId(spuId);

        //根据spuId查询spuDetail
        SpuDetailDTO spuDetailDTO = itemClient.querySpuDetailById(spuId);

        Map<String, Object> map = new HashMap<>();
        map.put("categories", categoryDTOS);
        map.put("brand", brandDTO);
        map.put("spuName", spuDTO.getName());
        map.put("subTitle", spuDTO.getSubTitle());
        map.put("skus", skuDTOS);
        map.put("detail", spuDetailDTO);
        map.put("specs", specGroupDTOS);


        return map;
    }

    //页面静态化  就是根据model渲染模版并保存在页面
    public void createItemHtml(Long id) {
        // 上下文，准备模型数据
        Context context = new Context();
        // 调用之前写好的加载数据方法
        context.setVariables(loadItemData(id));
        // 准备文件路径
        File dir = new File(itemDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                // 创建失败，抛出异常
                log.error("【静态页服务】创建静态页目录失败，目录地址：{}", dir.getAbsolutePath());
                throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
            }
        }
        File filePath = new File(dir, id + ".html");
        // 准备输出流
        try (PrintWriter writer = new PrintWriter(filePath, "UTF-8")) {
            templateEngine.process(itemTemplate, context, writer);
        } catch (IOException e) {
            log.error("【静态页服务】静态页生成失败，商品id：{}", id, e);
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }


    //删除静态页面
    public void deleteItemHtml(Long spuId) {
        File file = new File(itemDir,spuId + ".html");

        if (file.exists()){
            if (!file.delete()){
                log.error("【静态页服务】静态页删除失败，商品id：{}", spuId);
                throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
            }

        }

    }
}
